# -*- encoding=utf-8 -*-

import os
import shutil


def clone_by_suffix(dir_path, suffix):
    dir_path_fix = dir_path if dir_path[-1] == '/' else dir_path + '/'
    dir_base_name = os.path.basename(dir_path_fix[0:-1])
    current_dir = os.path.abspath('.')
    output_dir = dir_base_name + '_compiled'
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)

    if not os.path.isdir(output_dir + '/' + dir_base_name):
        os.mkdir(output_dir + '/' + dir_base_name)

    for parent, dirnames, filenames in os.walk(dir_path_fix):
        # for dirname in dirnames:
        # 	print("parent is:" + parent)
        # 	print("dirname is" + dirname)

        for filename in filenames:
            file_full_path = os.path.join(parent, filename)
            relative_path = parent.replace('\\', '/').replace(dir_path_fix, '')
            absolute_path = os.path.join(current_dir, output_dir, relative_path)
            file_new_path = os.path.join(absolute_path, filename)
            file_base_name = file_new_path[0:-2]
            so_file_path = file_base_name + 'so'
            c_file_path = file_base_name + 'c'
            # html_file_path = file_base_name + 'html'
            if not os.path.isdir(absolute_path) and relative_path.find('__pycache__') < 0:
                os.makedirs(absolute_path)

            if os.path.basename(parent) != '__pycache__':
                shutil.copy(file_full_path, file_new_path)

            if ((relative_path + filename) != 'main.py') and filename[0:-3].lower() != '__init__' and suffix.lower() == \
                    os.path.splitext(filename)[1].lower():
                # if ((relative_path + filename) != 'main.py') and suffix.lower() == os.path.splitext(filename)[1].lower():
                # print(dir_path_fix)
                # print(parent)
                # print(relative_path)
                # print(current_dir)
                # print(absolute_path)
                cython_cmd = '/usr/local/python3/bin/cython ' + file_new_path
                os.system(cython_cmd)
                gcc_cmd = 'gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I /usr/local/python3/include/python3.5m -o ' + so_file_path + ' ' + c_file_path
                os.system(gcc_cmd)
                os.system('rm ' + c_file_path)
                # os.system('rm ' + html_file_path)
                os.system('rm ' + file_new_path)
            # print(file_new_path)
            # print(cython_cmd)
            # print(gcc_cmd)

project_path = '/www/python/host'
clone_by_suffix(project_path, '.py')
# print(os.path.basename(dir_path))
